﻿using Assets.Scripts.DL.Consts;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Xml.Serialization;
using UnityEngine;
using UnityEngine.Audio;

namespace Assets.Scripts.DL.Mgrs {
	/// <summary>
	/// 随便找个物体挂上即可
	/// </summary>
	public class AudioManager : MonoBehaviour {

		public static AudioManager Instance { get; private set; }
		public AudioMixer audioMixer;//拖入，因为好像无法用资源加载
		public Dictionary<string, AudioClip> audioClipDic = new();


		private void Awake() {
			if (audioMixer == null) {
				Debug.Log("Not Found AudioMixer");
				return;
			}
			//audioMixer = ResLoader.LoadRes<AudioMixer>(PathStr.AudioMixer);
			Instance = this;
			var audioClips = ResLoader.LoadAllRes<AudioClip>(PathStr.Audio).ToList();

			foreach (var audio in audioClips) {
				audioClipDic.Add(audio.name, audio);
				//Debug.Log(audio.name);
			}
		}

		public static void Play(AudioSource source, string clipName, bool isLoop = false) {
			if (!Instance.audioClipDic.ContainsKey(clipName)) {
				Debug.LogError("不存在" + clipName + "音频");
				return;
			}
			source.clip = Instance.audioClipDic[clipName];
			source.loop = isLoop;
			source.Play();
		}

		public static void Stop(AudioSource source) {
			source.Stop();
		}

		public static void SetSouceGroup(AudioSource source, string groupName) {
			source.outputAudioMixerGroup = Instance.audioMixer.FindMatchingGroups(groupName)[0];
		}

		/// <summary>
		/// Volume Range 0~20
		/// </summary>
		public static void SetGroupVolum(string groupName, float volume) {
			Instance.audioMixer.SetFloat(groupName, volume);
		}

		public static float GetGroupVolum(string groupName) {
			Instance.audioMixer.GetFloat(groupName, out float ret);
			return ret;
		}
	}

}
